package com.clouds.wms.pur;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.clouds.wms.bean.Cmsmd;
import com.clouds.wms.bean.Cmsmk;
import com.clouds.wms.bean.Purmh;
import com.clouds.wms.bean.Purmi;
import com.clouds.wms.bean.Purmj;
import com.clouds.wms.exception.SysException;
import com.clouds.wms.service.CmsmkService;
import com.clouds.wms.service.PurmiService;
import com.clouds.wms.util.ExcelImportChecker;
import com.clouds.wms.util.ExcelUtil;
import com.clouds.wms.util.Function;
import com.clouds.wms.util.PagesBean;
import com.clouds.wms.util.RequestHelper;
import com.clouds.wms.util.SysParams;
import com.clouds.wms.util.UploadFile;

@Controller
@RequestMapping("/purmi")
public class PurmiController {
	private Log log = LogFactory.getLog(getClass());
	@Resource(name="purmiService")
	private PurmiService purmiService;
	@Resource(name="cmsmkService")
	private CmsmkService cmsmkService;
	@RequestMapping(value = "/purmiMain.xhtml")
	public String purmiMain(HttpServletRequest request, HttpServletResponse response, Model model) throws SysException {
		return "pur/purmi";
	}
	@RequestMapping(value = "/purmiList.xhtml")
	public String purmaList(HttpServletRequest request, HttpServletResponse response, Model model) throws SysException {
		String miaa = RequestHelper.getString(request, "miaa");
		String miab = RequestHelper.getString(request, "miab");
		String miad = RequestHelper.getString(request, "miad");
		String startMiac = RequestHelper.getString(request, "startMiac");
		String endMiac = RequestHelper.getString(request, "endMiac");
		int pageNumber = RequestHelper.getInt(request, "page", 1);// 要跳转的页号
		int pageSize = RequestHelper.getInt(request, "rows", 10);// 一页的条数
		PagesBean pb = purmiService.getPurmiList(miaa, miab, startMiac, endMiac, miad, pageNumber, pageSize);
		List<Purmi> list = (List<Purmi>) pb.getData();
		int count = pb.getCount();
		Map<String,Object> paraMap = new HashMap<String,Object>();
		paraMap.put("total", count);
		paraMap.put("rows", list);
		try {
			Function.toJson(response, paraMap);
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		return null;
	}
	@RequestMapping(value = "/purmjMain.xhtml")
	public String purmjMain(HttpServletRequest request, HttpServletResponse response, Model model) throws SysException {
		model.addAttribute("purmi", purmiService.getPurmi(RequestHelper.getString(request, "miaa")));
		return "pur/purmj";
	}
	@RequestMapping(value = "/purmjList.xhtml")
	public String purmjList(HttpServletRequest request, HttpServletResponse response, Model model) throws SysException {
		String mjaa = RequestHelper.getString(request, "mjaa");
		int pageNumber = RequestHelper.getInt(request, "page", 1);// 要跳转的页号
		int pageSize = RequestHelper.getInt(request, "rows", 10);// 一页的条数
		PagesBean pb = purmiService.getPurmjList(mjaa, pageNumber, pageSize);
		List<Purmj> list = (List<Purmj>) pb.getData();
		int count = pb.getCount();
		Map<String,Object> paraMap = new HashMap<String,Object>();
		paraMap.put("total", count);
		paraMap.put("rows", list);
		try {
			Function.toJson(response, paraMap);
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		return null;
	}
	/**
	 * 删除采购单
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws SysException
	 * @throws IOException 
	 */
	@RequestMapping(value = "/delPurmimj.xhtml", method = RequestMethod.POST)
	public String delPurmimj(HttpServletRequest request, HttpServletResponse response, Model model, Purmh purmh) throws SysException, IOException {
		String miaa = RequestHelper.getString(request, "miaa");
		Cmsmd globalUmUser = (Cmsmd)request.getSession().getAttribute("globalUmUser");
		response.setContentType("text/xml;charset=utf-8");
		response.setHeader("Pragma", "No-cache");
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		purmiService.delPurmimj(miaa);
		Cmsmk cmsmk = new Cmsmk();
		cmsmk.setMkab(String.valueOf(globalUmUser.getMdaa()));
		cmsmk.setMkac(globalUmUser.getMdac());
		cmsmk.setMkad("删除了编号为[" + purmh.getMhab() + "]的收货清单!");
		cmsmk.setMkae(new Date());
		cmsmk.setMkaf(request.getRemoteAddr());
		cmsmkService.saveCmsmk(cmsmk);
		out.print("success");
		return null;
	}
	/**
	 * 导入excel
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws SysException
	 * @throws IOException 
	 */
	@RequestMapping(value = "/importExcel.xhtml", method = RequestMethod.POST)
	public String importExcel(HttpServletRequest request, HttpServletResponse response, Model model) throws SysException, IOException {
		String fileName = RequestHelper.getString(request, "fileName");
		response.setContentType("text/xml;charset=utf-8");
		response.setHeader("Pragma", "No-cache");
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		String path = UploadFile.attRootPath + UploadFile.SYSTEM_LINE + fileName;
		File f = new File(path);
		if(f.exists()){
			out.print("isExists");
			return null;
		}else{
			out.print("success");
			return null;
		}
	}
	/**
	 * 导入excel
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws SysException
	 * @throws IOException 
	 */
	@RequestMapping(value = "/saveExcel.xhtml", method = RequestMethod.POST)
	public String saveExcel(HttpServletRequest request, HttpServletResponse response, Model model) throws SysException, IOException {
		try{
			String miad = RequestHelper.getString(request, "miad");
			Map<String,Object> retJsonMap = new HashMap<String,Object>();
			String messages = null;
			String path = "";
			String tempFileName="";
			CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			commonsMultipartResolver.setDefaultEncoding("utf-8");
			if(commonsMultipartResolver.isMultipart(request)) {
				MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
				CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("fileUpload");
				
				if(file != null && file.getSize() != 0) {
					UploadFile upload = new UploadFile();
					upload.init();
					tempFileName = file.getOriginalFilename();
					path = UploadFile.attRootPath + UploadFile.SYSTEM_LINE + tempFileName;
					File f = new File(path);
					if(f.exists()&&f.delete()){
						String sql = "select * from purmi where miae = '"+tempFileName+"'";
						Purmi pur = purmiService.getPurmiBySql(sql);
						if(pur!=null&&pur.getMiaa()!=null&&"".equals(pur.getMiaa())){
							purmiService.delPurmimj(pur.getMiaa());
						}
//						purmiService.delPurmimj(pur.getMiaa());
					}
					path = upload.load(file, path);	
				}
			}
			if(path.equals("")) {
				messages = "上传失败。";
				retJsonMap.put("msg", messages);
				retJsonMap.put("status", "fail");
				Function.toJsonObjectForFileUpload(response, retJsonMap);
				return null;
			}
			ExcelUtil excelUtil = new ExcelUtil();
			ExcelImportChecker checker = new ExcelImportChecker("/com/clouds/wms/pur/PurmiExcelImportChecker.xml");
			Object[] objRet = excelUtil.readExcel(path,checker);
			String errMsg = (String)objRet[1];
			if(errMsg!=null){
				File f = new File(path);
				f.delete();
				retJsonMap.put("msg", errMsg);
				retJsonMap.put("status", "fail");
				Function.toJsonObjectForFileUpload(response, retJsonMap);
				return null;
			}else{
				@SuppressWarnings("unchecked")
				List<List<Object>> datas = (List<List<Object>>) objRet[0];
				
				if(datas == null) {
					File f = new File(path);
					f.delete();
					messages = "上传失败。";
					retJsonMap.put("msg", messages);
					retJsonMap.put("status", "fail");
					Function.toJsonObjectForFileUpload(response, retJsonMap);
					return null;
				}
				if(datas.size()==0) {
					File f = new File(path);
					f.delete();
					messages = "收货清单中没有要导入的信息。";
					retJsonMap.put("msg", messages);
					retJsonMap.put("status", "fail");
					Function.toJsonObjectForFileUpload(response, retJsonMap);
					return null;
				}
				List<Purmj> purmjList = new ArrayList<Purmj>();
				for(int i = 0; i < datas.size(); i++) {
					List<Object> objList = datas.get(i);
					Object[] purmjRetObj = getPurmjs(miad,objList,i);
					if(purmjRetObj[0]==null){
						retJsonMap.put("msg", purmjRetObj[1]);
						retJsonMap.put("status", "fail");
						Function.toJsonObjectForFileUpload(response, retJsonMap);
						return null;
					}else{
						purmjList.add((Purmj)purmjRetObj[0]);
					}
				}
				Purmi purmi = new Purmi();
				purmi.setMiaa(Function.getDateString(new Date()).replace("-", "")+(int)Math.random()*10);
				purmi.setMiab(SysParams.AUDIT_YARDS_AUDIT);
				purmi.setMiac(Function.getDateString(new Date()));
				purmi.setMiad(miad);
				purmi.setMiae(tempFileName);
				purmiService.savePurmjList(purmi,purmjList);
				messages = "导入成功。";
				retJsonMap.put("msg", messages);
				retJsonMap.put("status", "success");
				Function.toJsonObjectForFileUpload(response, retJsonMap);
				return null;
			}
		}catch(Exception e){
			Map<String,Object> retJsonMap = new HashMap<String,Object>();
			retJsonMap.put("msg", "导入物品信息发生了错误,请将以下信息发送给系统管理员："+e.toString());
			retJsonMap.put("status", "fail");
			Function.toJsonObjectForFileUpload(response, retJsonMap);
			e.printStackTrace();
	
		}
		return null;
	}
	private Object[] getPurmjs(String miad,List<Object> colsList,int rowNum){
		Purmj purmj = null;
		String[] mjabGet = ExcelUtil.getColStringValue(colsList, 0, rowNum); // 采购订单单号
		String mjab = mjabGet[0];
		if(mjab==null)return new Object[]{null,mjabGet[1]};
		Object[] mjacGet = ExcelUtil.getColIntegerValue(colsList, 1, rowNum); // 行号
		int mjac = (Integer) mjacGet[0];
		if(mjac<0)return new Object[]{null,mjacGet[1]};
		
		String[] mjadGet = ExcelUtil.getColStringValue(colsList, 2, rowNum); // 物品编号
		String mjad = mjadGet[0];
		if(mjad==null)return new Object[]{null,mjadGet[1]};
		
		String[] mjaeGet = ExcelUtil.getColStringValue(colsList, 3, rowNum); // 仓库
		String mjae = mjaeGet[0];
		if(mjae==null)return new Object[]{null,mjaeGet[1]};
		
		Object[] mjafGet = ExcelUtil.getColDoubleValue(colsList, 4, rowNum); // 数量
		double mjaf = (Double) mjafGet[0];
		if(mjaf<0)return new Object[]{null,mjafGet[1]};
		
		String[] mjagGet = ExcelUtil.getColStringValue(colsList, 5, rowNum); // 包号
		String mjag = mjagGet[0];
		if(mjag==null)return new Object[]{null,mjagGet[1]};
		
		String[] mjahGet = ExcelUtil.getColStringValue(colsList, 6, rowNum); // Lot no Trading Unit
		String mjah = mjahGet[0];
		if(mjah==null)return new Object[]{null,mjahGet[1]};
		
		String[] mjaiGet = ExcelUtil.getColStringValue(colsList, 7, rowNum); // 手册号
		String mjai = mjaiGet[0];
		if(mjai==null)return new Object[]{null,mjaiGet[1]};
		
		String[] mjajGet = ExcelUtil.getColStringValue(colsList, 8, rowNum); // Internal Lot no
		String mjaj = mjajGet[0];
		if(mjaj==null)return new Object[]{null,mjajGet[1]};
		
		String[] mjakGet = ExcelUtil.getColStringValue(colsList, 9, rowNum); // net Weight
		String mjak = mjakGet[0];
		if(mjak==null)return new Object[]{null,mjakGet[1]};
		
		String[] mjalGet = ExcelUtil.getColStringValue(colsList, 10, rowNum); // Gross Weight
		String mjal = mjalGet[0];
		if(mjal==null)return new Object[]{null,mjalGet[1]};
		
		String[] mjamGet = ExcelUtil.getColStringValue(colsList, 11, rowNum); // Expirati On Date
		String mjam = mjamGet[0];
		if(mjam==null)return new Object[]{null,mjamGet[1]};
		
		String[] mjanGet = ExcelUtil.getColStringValue(colsList, 12, rowNum); // New Lot
		String mjan = mjanGet[0];
		if(mjan==null)return new Object[]{null,mjanGet[1]};
		
		String[] mjaoGet = ExcelUtil.getColStringValue(colsList, 13, rowNum); // New Lot No Trading Unit
		String mjao = mjanGet[0];
		if(mjao==null)return new Object[]{null,mjaoGet[1]};
		
		String[] mjapGet = ExcelUtil.getColStringValue(colsList, 14, rowNum); // New Trading unit No
		String mjap = mjapGet[0];
		if(mjap==null)return new Object[]{null,mjapGet[1]};
		
		String[] mjaqGet = ExcelUtil.getColStringValue(colsList, 14, rowNum); // New Customs Handbook No
		String mjaq = mjapGet[0];
		if(mjaq==null)return new Object[]{null,mjaqGet[1]};
		
		purmj = new Purmj();
		purmj.setMjaa(miad);
		purmj.setMjab(mjab);
		purmj.setMjac(mjac);
		purmj.setMjad(mjad);
		purmj.setMjae(mjae);
		purmj.setMjaf(mjaf);
		purmj.setMjag(mjag);
		purmj.setMjah(mjah);
		purmj.setMjai(mjai);
		purmj.setMjaj(mjaj);
		purmj.setMjak(mjak);
		purmj.setMjal(mjal);
		purmj.setMjam(mjam);
		purmj.setMjan(mjan);
		purmj.setMjao(mjao);
		purmj.setMjap(mjap);
		purmj.setMjaq(mjaq);
		
		return new Object[]{purmj,null};
	}
}
